package tv.drplay.course.utils

import android.app.Application
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import com.baidu.mobstat.StatService
import com.mowan365.common.BuildConfig
import com.mowan365.common.data.User
import io.sentry.Sentry
import io.sentry.android.AndroidSentryClientFactory
import top.kpromise.contentprovider.CommonData
import top.kpromise.glide.ImageLoader
import top.kpromise.http.HttpManager
import top.kpromise.ibase.Config
import top.kpromise.ibase.IApplication
import top.kpromise.model.ShortCutInfoModel
import top.kpromise.utils.ActivityLifeCallBack
import top.kpromise.utils.CommonTools
import top.kpromise.utils.ILog
import tv.drplay.course.R
import tv.drplay.course.crash.CrashHandler
import tv.drplay.course.hook.BaiduAnalytics
import tv.drplay.course.hook.BaiduAnalyticsForFragment

fun initSentrySdk(app: Application) {
    Sentry.init(AndroidSentryClientFactory(app))
    val crashHandler = CrashHandler(app)
    Thread.setDefaultUncaughtExceptionHandler(crashHandler)

    if (!User.isLogin()) return
    val userInfo = User.userInfo
    val oldUser = Sentry.getContext()?.user
    val user = io.sentry.event.User(oldUser?.id, userInfo?.mobile, oldUser?.ipAddress, userInfo?.nickName)
    Sentry.getContext()?.user = user
}

fun initBaiduAnalytics() {
    var channel = CommonData.get("app_channel")
    if (channel == null) {
        channel = CommonTools.getMetaData(IApplication.app, "BaiduMobAd_CHANNEL")
        ILog.e("===channel", "get from xml $channel")
        CommonData.put("app_channel", channel)
    }
    if (channel != null) {
        ILog.e("===channel", "set $channel")
        StatService.setAppChannel(IApplication.app, channel, true)
    }
    //if (BuildConfig.isDebug) return
    StatService.start(IApplication.app)
    StatService.setLogSenderDelayed(10)
    StatService.autoTrace(IApplication.app)
    StatService.setDebugOn(BuildConfig.isDebug)

    val baiduAnalytics = BaiduAnalytics()
    Config.lifecycleCallback = ActivityLifeCallBack(baiduAnalytics)
    Config.fragmentLifeCycleCall = BaiduAnalyticsForFragment()
}

fun initHttp() {
    HttpManager.setBaseUrl(BuildConfig.serverUrl)
    HttpManager.setShowLog(true)
    HttpManager.addCommonParameter("pageSize", "20")
    ILog.isShowLog = BuildConfig.isDebug or BuildConfig.DEBUG
    if (User.isLogin()) {
        HttpManager.addCommonHeader("Authorization", "${User.loginTokenModel?.tokenType} ${User.loginTokenModel?.accessToken}")
    }
}

//fun initPush(callback: ThreadUtils.ICallBack<String>? = null) {
//    val pushConfig = PushConfig()
////    pushConfig.xiaomiAppId = "2882303761517930039"
////    pushConfig.xiaomiAppKey = "5661793091039"
////    pushConfig.oppoAppKey = "a5fd65d6c1f24000ae0fafec4c5ef961"
////    pushConfig.oppoAppSecret = "334e0aca6d564014a8d0652daee70339"
//    AliMessageManager.pushConfig = pushConfig
//    AliMessageManager.initCloudChannel(object : ThreadUtils.ICallBack<String> {
//        override fun onResult(result: String?) {
//            callback?.onResult(result)
////            AliMessageManager.setDoNotDisturb(22, 0, 7, 0)
//        }
//    }, R.mipmap.ic_launcher)
//}

fun initCoreData() {
    User.initData()
}

fun initImageLoader() {
    ImageLoader.type = object : ImageLoader.ImageLoadType() {
        override fun isAliYunServer(url: String?): Boolean {
            return url?.startsWith("https://media.mowan365.com") ?: false
        }
    }
}

//fun initThirdSdk() {
//    val thirdAppId = ThirdAppId("wx253f7057b4ccd8b9", null, null)
//    ThirdUserConfig.appId = thirdAppId
//}

fun initShortCuts(app: Application) {
    if (BuildConfig.DEBUG || BuildConfig.isDebug) {
        val intent = Intent()
        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        intent.data = Uri.fromParts("package", app.packageName, null)
        val settingsInfo = ShortCutInfoModel("settings", R.mipmap.ic_launcher, intent, "应用信息")

//        val bucketList = Intent(app, BucketListActivity::class.java)
//        bucketList.action = Intent.CATEGORY_LAUNCHER
//        val bucketListInfo = ShortCutInfoModel("bucketList", R.mipmap.ic_launcher, bucketList, "相册")
//        CommonTools.shortCut(arrayListOf(settingsInfo, bucketListInfo))
        CommonTools.shortCut(arrayListOf(settingsInfo))
    }
}

fun syncCookie(): Boolean {
    val url = BuildConfig.h5Url
    val cookie = "device=android;token=${User.loginTokenModel?.accessToken}"
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(IApplication.app)
    }
    val cookieManager = CookieManager.getInstance()
    try {       //  utest 显示有一款手机setAcceptCookie 时找不到方法
        cookieManager.setAcceptCookie(true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    if (Build.VERSION.SDK_INT < 21) {
        CookieSyncManager.getInstance().sync()
    } else {
        CookieManager.getInstance().flush()
    }
    val cookies = cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    for (keyValue in cookies) {
        cookieManager.setCookie(url, keyValue)
    }
    val newCookie = cookieManager.getCookie(url)
    return top.kpromise.utils.StringUtils.isEmpty(newCookie)
}